// 增强版JavaScript - Ultra版B站智能学习平台

// 全局变量
let currentAnalysisData = null;
let learningStats = {
    totalVideos: 0,
    totalTime: 0,
    learningStreak: 0,
    skillsMastered: 0
};

const API_BASE = window.location.origin;

// DOM元素
const elements = {
    // 导航相关
    navBtns: document.querySelectorAll('.nav-btn'),
    contentSections: document.querySelectorAll('.content-section'),

    // 分析相关
    videoUrl: document.getElementById('videoUrl'),
    analyzeBtn: document.getElementById('analyzeBtn'),
    batchAnalyzeBtn: document.getElementById('batchAnalyzeBtn'),
    batchModal: document.getElementById('batchModal'),
    batchInput: document.getElementById('batchInput'),

    // 系列课程相关
    uploaderId: document.getElementById('uploaderId'),
    analyzeSeriesBtn: document.getElementById('analyzeSeriesBtn'),
    seriesResults: document.getElementById('seriesResults'),

    // 学习路径相关
    learningTopic: document.getElementById('learningTopic'),
    learningLevel: document.getElementById('learningLevel'),
    createPathBtn: document.getElementById('createPathBtn'),
    pathResults: document.getElementById('pathResults'),

    // 知识图谱相关
    knowledgeTopic: document.getElementById('knowledgeTopic'),
    buildMapBtn: document.getElementById('buildMapBtn'),
    mapResults: document.getElementById('mapResults'),

    // 统计相关
    totalVideos: document.getElementById('totalVideos'),
    totalTime: document.getElementById('totalTime'),
    learningStreak: document.getElementById('learningStreak'),
    skillsMastered: document.getElementById('skillsMastered'),

    // 其他
    toast: document.getElementById('toast')
};

// ================ 事件监听器 ================

// 导航切换
elements.navBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        const tabName = btn.dataset.tab;
        switchTab(tabName);
    });
});

// 分析功能
elements.analyzeBtn?.addEventListener('click', handleAnalyze);
elements.batchAnalyzeBtn?.addEventListener('click', openBatchModal);
elements.createPathBtn?.addEventListener('click', createLearningPath);
elements.buildMapBtn?.addEventListener('click', buildKnowledgeMap);
elements.analyzeSeriesBtn?.addEventListener('click', analyzeSeries);

// 回车键触发分析
elements.videoUrl?.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        handleAnalyze();
    }
});

// 示例链接点击
document.querySelectorAll('.example-link').forEach(link => {
    link.addEventListener('click', (e) => {
        e.preventDefault();
        elements.videoUrl.value = e.target.dataset.url;
        elements.videoUrl.focus();
    });
});

// ================ 主要功能函数 ================

// 标签页切换
function switchTab(tabName) {
    // 更新导航按钮状态
    elements.navBtns.forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.tab === tabName) {
            btn.classList.add('active');
        }
    });

    // 显示对应内容
    elements.contentSections.forEach(section => {
        section.classList.remove('active');
        if (section.id === tabName + 'Tab') {
            section.classList.add('active');
        }
    });
}

// 处理视频分析
async function handleAnalyze() {
    const url = elements.videoUrl.value.trim();

    if (!url) {
        showToast('请输入B站视频链接', 'error');
        elements.videoUrl.focus();
        return;
    }

    // 验证URL格式
    if (!url.includes('bilibili.com') && !url.includes('b23.tv') && !url.startsWith('BV')) {
        showToast('请输入有效的B站视频链接或BV号', 'error');
        return;
    }

    showLoading();

    try {
        const response = await fetch(`${API_BASE}/api/analyze`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ url })
        });

        const result = await response.json();

        if (!result.success) {
            throw new Error(result.error || '分析失败');
        }

        // 更新统计
        learningStats.totalVideos++;
        updateLearningStats();

        // 显示结果
        currentAnalysisData = result.data;
        displayAnalysisResults(result.data);

        // 自动获取推荐
        await getRecommendations(result.data.video_info.bvid);

        showToast('✨ 分析完成！已生成四大板块深度报告', 'success');

    } catch (error) {
        console.error('分析错误:', error);
        showError(error.message || '分析过程中出现错误，请检查链接后重试');
        showToast('分析失败：' + error.message, 'error');
    }
}

// 获取相关推荐
async function getRecommendations(bvid) {
    try {
        const response = await fetch(`${API_BASE}/api/recommendations`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                bvid: bvid,
                count: 6
            })
        });

        const result = await response.json();

        if (result.success && result.data.recommendations.length > 0) {
            displayRecommendations(result.data.recommendations);
        }
    } catch (error) {
        console.error('获取推荐失败:', error);
    }
}

// 显示推荐视频
function displayRecommendations(recommendations) {
    const recommendationsSection = document.getElementById('recommendationsSection');
    const recommendationGrid = document.getElementById('recommendationGrid');

    if (!recommendationsSection || !recommendationGrid) return;

    const html = recommendations.map(video => `
        <div class="recommendation-card" onclick="analyzeVideo('${video.bvid}')">
            <img class="recommendation-thumbnail" src="${video.pic || '/placeholder.jpg'}" alt="${video.title}">
            <div class="recommendation-info">
                <div class="recommendation-title">${video.title}</div>
                <div class="recommendation-meta">
                    <span class="recommendation-author">${video.author || '未知UP主'}</span>
                    <div class="recommendation-stats">
                        <span><i class="fas fa-play"></i> ${formatNumber(video.play || 0)}</span>
                        <span><i class="fas fa-thumbs-up"></i> ${formatNumber(video.like || 0)}</span>
                    </div>
                </div>
            </div>
        </div>
    `).join('');

    recommendationGrid.innerHTML = html;
    recommendationsSection.classList.remove('hidden');
}

// 分析推荐视频
function analyzeVideo(bvid) {
    elements.videoUrl.value = `https://www.bilibili.com/video/${bvid}`;
    switchTab('analyze');
    handleAnalyze();
}

// 批量分析功能
function openBatchModal() {
    elements.batchModal.classList.remove('hidden');
}

function closeBatchModal() {
    elements.batchModal.classList.add('hidden');
    elements.batchInput.value = '';
}

async function startBatchAnalysis() {
    const input = elements.batchInput.value.trim();
    if (!input) {
        showToast('请输入视频链接', 'error');
        return;
    }

    const bvList = input.split('\n')
        .map(line => line.trim())
        .filter(line => line.length > 0);

    if (bvList.length === 0) {
        showToast('没有有效的视频链接', 'error');
        return;
    }

    if (bvList.length > 10) {
        showToast('批量分析最多支持10个视频', 'warning');
        return;
    }

    closeBatchModal();
    showBatchLoading(bvList.length);

    try {
        const response = await fetch(`${API_BASE}/api/batch/analyze`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                bv_list: bvList,
                analysis_type: 'summary'
            })
        });

        const result = await response.json();

        if (result.success) {
            displayBatchResults(result.data);
            learningStats.totalVideos += result.data.completed;
            updateLearningStats();

            showToast(`批量分析完成！成功分析 ${result.data.completed} 个视频`, 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        console.error('批量分析错误:', error);
        showToast('批量分析失败：' + error.message, 'error');
    }
}

// 系列课程分析
async function analyzeSeries() {
    const uid = elements.uploaderId.value.trim();

    if (!uid) {
        showToast('请输入UP主UID或用户名', 'error');
        elements.uploaderId.focus();
        return;
    }

    showLoading();

    try {
        const response = await fetch(`${API_BASE}/api/series/analyze`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ uid: uid })
        });

        const result = await response.json();

        if (result.success) {
            displaySeriesResults(result.data);
            showToast('✅ 系列课程分析完成！', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        console.error('系列分析错误:', error);
        showToast('系列分析失败：' + error.message, 'error');
    }
}

// 创建学习路径
async function createLearningPath() {
    const topic = elements.learningTopic.value.trim();
    const level = elements.learningLevel.value;

    if (!topic) {
        showToast('请输入学习主题', 'error');
        elements.learningTopic.focus();
        return;
    }

    showLoading();

    try {
        const response = await fetch(`${API_BASE}/api/learning/path`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                topic: topic,
                level: level
            })
        });

        const result = await response.json();

        if (result.success) {
            displayLearningPathResults(result.data);
            showToast('🎯 学习路径生成成功！', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        console.error('创建学习路径错误:', error);
        showToast('创建学习路径失败：' + error.message, 'error');
    }
}

// 构建知识图谱
async function buildKnowledgeMap() {
    const topic = elements.knowledgeTopic.value.trim();

    if (!topic) {
        showToast('请输入知识领域', 'error');
        elements.knowledgeTopic.focus();
        return;
    }

    showLoading();

    try {
        // 先搜索相关视频
        const searchResponse = await fetch(`${API_BASE}/api/search/advanced`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                keyword: topic,
                filters: {
                    duration: 'medium',
                    order: 'relevance'
                }
            })
        });

        const searchResult = await searchResponse.json();

        if (!searchResult.success) {
            throw new Error(searchResult.error);
        }

        // 生成知识图谱
        const mapResponse = await fetch(`${API_BASE}/api/knowledge/map`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                topic: topic,
                videos: searchResult.data.results
            })
        });

        const mapResult = await mapResponse.json();

        if (mapResult.success) {
            displayKnowledgeMapResults(mapResult.data);
            showToast('🕸️ 知识图谱构建完成！', 'success');
        } else {
            throw new Error(mapResult.error);
        }
    } catch (error) {
        console.error('构建知识图谱错误:', error);
        showToast('构建知识图谱失败：' + error.message, 'error');
    }
}

// ================ 显示函数 ================

function displayAnalysisResults(data) {
    // 这里集成原有的显示逻辑
    console.log('分析结果:', data);

    // 更新UI显示分析结果
    hideLoading();

    // 显示结果区域
    const resultSection = document.getElementById('resultSection');
    if (resultSection) {
        resultSection.classList.remove('hidden');
    }
}

function displaySeriesResults(data) {
    if (!elements.seriesResults) return;

    const html = `
        <div class="series-content">
            <h3><i class="fas fa-user-circle"></i> UP主：${data.uploader_info.name}</h3>
            <p>粉丝数：${formatNumber(data.uploader_info.fans)} | 总视频数：${data.total_videos}</p>

            ${data.series_courses.length > 0 ? `
                <h4>📚 系列课程 (${data.series_courses.length}个)</h4>
                <div class="series-list">
                    ${data.series_courses.map(series => `
                        <div class="series-item">
                            <h5>${series.title}</h5>
                            <p>${series.video_count} 个视频 • ${formatNumber(series.total_views)} 播放量</p>
                        </div>
                    `).join('')}
                </div>
            ` : '<p>暂无系列课程</p>'}

            <h4>🔥 热门视频</h4>
            <div class="top-videos">
                ${data.top_videos.slice(0, 5).map(video => `
                    <div class="video-item">
                        <strong>${video.title}</strong>
                        <span>${formatNumber(video.view)} 播放</span>
                    </div>
                `).join('')}
            </div>
        </div>
    `;

    elements.seriesResults.innerHTML = html;
    elements.seriesResults.classList.remove('hidden');
    hideLoading();
}

function displayLearningPathResults(data) {
    if (!elements.pathResults) return;

    const html = `
        <div class="path-content">
            <h3>🎯 ${data.topic} - ${data.user_level}学习路径</h3>
            <p>预计学习时间：${data.estimated_time_minutes} 分钟 | 包含 ${data.total_videos} 个视频</p>

            <h4>📋 学习目标</h4>
            <ul>
                ${data.learning_objectives.map(obj => `<li>${obj}</li>`).join('')}
            </ul>

            <h4>🚀 学习阶段</h4>
            <div class="learning-stages">
                ${data.learning_stages.map((stage, index) => `
                    <div class="stage-item">
                        <h5>阶段 ${index + 1}: ${stage.stage}</h5>
                        <p>${stage.description}</p>
                        <div class="stage-videos">
                            ${stage.videos.slice(0, 3).map(video =>
                                `<span class="video-tag">${video.title}</span>`
                            ).join('')}
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>
    `;

    elements.pathResults.innerHTML = html;
    elements.pathResults.classList.remove('hidden');
    hideLoading();
}

function displayKnowledgeMapResults(data) {
    if (!elements.mapResults) return;

    const html = `
        <div class="map-content">
            <h3>🕸️ ${data.topic} 知识图谱</h3>
            <p>包含 ${data.total_concepts} 个核心概念</p>

            <div class="knowledge-nodes">
                <h4>📚 核心概念</h4>
                <div class="nodes-grid">
                    ${data.nodes.map(node => `
                        <div class="node-item" style="background: linear-gradient(135deg, rgba(0,161,214,0.1), rgba(79,195,247,0.1));">
                            <strong>${node.name}</strong>
                            <p>难度：${'⭐'.repeat(node.difficulty)}</p>
                            <small>${node.description}</small>
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
    `;

    elements.mapResults.innerHTML = html;
    elements.mapResults.classList.remove('hidden');
    hideLoading();
}

function displayBatchResults(data) {
    console.log('批量分析结果:', data);
    showToast(`批量分析完成：成功 ${data.completed}，失败 ${data.failed}`, 'success');
}

// ================ 加载和错误处理 ================

function showLoading() {
    // 显示加载动画
    const loadingSection = document.getElementById('loadingSection');
    if (loadingSection) {
        loadingSection.classList.remove('hidden');
    }

    // 隐藏结果区域
    const resultSection = document.getElementById('resultSection');
    if (resultSection) {
        resultSection.classList.add('hidden');
    }
}

function showBatchLoading(count) {
    showToast(`正在批量分析 ${count} 个视频，请稍候...`, 'info');
}

function hideLoading() {
    const loadingSection = document.getElementById('loadingSection');
    if (loadingSection) {
        loadingSection.classList.add('hidden');
    }
}

function showError(message) {
    hideLoading();

    const errorSection = document.getElementById('errorSection');
    const errorMessage = document.getElementById('errorMessage');

    if (errorSection && errorMessage) {
        errorMessage.textContent = message;
        errorSection.classList.remove('hidden');
    }
}

// ================ 工具函数 ================

function showToast(message, type = 'info') {
    if (!elements.toast) return;

    const toast = elements.toast;
    const messageSpan = toast.querySelector('.toast-message') || toast;

    if (messageSpan !== toast) {
        messageSpan.textContent = message;
    } else {
        toast.textContent = message;
    }

    toast.className = `toast ${type}`;
    toast.classList.remove('hidden');

    setTimeout(() => {
        toast.classList.add('hidden');
    }, 3500);
}

function formatNumber(num) {
    if (num >= 100000000) {
        return (num / 100000000).toFixed(2) + '亿';
    }
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
    }
    return num.toLocaleString('zh-CN');
}

function updateLearningStats() {
    if (elements.totalVideos) elements.totalVideos.textContent = learningStats.totalVideos;
    if (elements.totalTime) elements.totalTime.textContent = learningStats.totalTime;
    if (elements.learningStreak) elements.learningStreak.textContent = learningStats.learningStreak;
    if (elements.skillsMastered) elements.skillsMastered.textContent = learningStats.skillsMastered;
}

// ================ 页面加载完成 ================

document.addEventListener('DOMContentLoaded', () => {
    console.log('%c🚀 BiliBili智能学习平台 Ultra版已就绪', 'color: #00A1D6; font-size: 16px; font-weight: bold;');
    console.log('%c✨ Powered by Qwen3-Omni AI & bilibili-api', 'color: #FB7299; font-size: 14px;');

    // 初始化统计
    updateLearningStats();

    // 聚焦输入框
    if (elements.videoUrl) {
        elements.videoUrl.focus();
    }

    // 检查URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const videoUrl = urlParams.get('url');
    if (videoUrl && elements.videoUrl) {
        elements.videoUrl.value = videoUrl;
        showToast('已自动填入视频链接，点击"智能分析"即可', 'info');
    }

    // 加载保存的学习数据
    loadLearningData();
});

// 加载学习数据
function loadLearningData() {
    try {
        const saved = localStorage.getItem('bilibili_learning_stats');
        if (saved) {
            learningStats = { ...learningStats, ...JSON.parse(saved) };
            updateLearningStats();
        }
    } catch (error) {
        console.error('加载学习数据失败:', error);
    }
}

// 保存学习数据
function saveLearningData() {
    try {
        localStorage.setItem('bilibili_learning_stats', JSON.stringify(learningStats));
    } catch (error) {
        console.error('保存学习数据失败:', error);
    }
}

// 监听页面关闭，保存数据
window.addEventListener('beforeunload', saveLearningData);

// 键盘快捷键
document.addEventListener('keydown', (e) => {
    // Ctrl+Enter 快速分析
    if (e.ctrlKey && e.key === 'Enter') {
        if (elements.videoUrl === document.activeElement) {
            handleAnalyze();
        }
    }

    // Esc 关闭模态框
    if (e.key === 'Escape') {
        closeBatchModal();
    }
});

// 阻止页面刷新时的警告
window.addEventListener('beforeunload', (e) => {
    if (elements.batchModal && !elements.batchModal.classList.contains('hidden')) {
        e.preventDefault();
        e.returnValue = '批量分析正在进行中，确定要离开吗？';
    }
});